/**
 *  @author Ion Morozan
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.dddforandroid.design;

import java.io.IOException;
import java.text.ParseException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.dddforandroid.database.R;
import com.dddforandroid.database.local.ReadNote;
import com.dddforandroid.database.server.NotePad.Notes;
import com.dddforandroid.database.server.SyncServerDatabase;

public class CurrentTasksActivity extends Activity {

	private ListView list;
	/* The ServerDatabase object */
	private SyncServerDatabase nosql;

	public static DefaultHttpClient authClient = new DefaultHttpClient();

	public static ImageButton sync;

	public static ProgressDialog progress;

	public Account account = null;
	public int flag = 0;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tasks_list);

		list = (ListView) findViewById(R.id.mainlist);
		list.setItemsCanFocus(false);

		nosql = new SyncServerDatabase();

		account = (Account) getIntent().getExtras().get("account");

		progress = ProgressDialog.show(CurrentTasksActivity.this, "",
				"Getting data from server");

		new ClientAuthentication(this.getApplicationContext(), nosql)
				.execute(account);

		sync = (ImageButton) findViewById(R.id.sync);
		sync.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) { 

				progress = ProgressDialog.show(CurrentTasksActivity.this, "",
						"Getting data from server");
				new ReadNote(getApplicationContext(), nosql, list)
						.execute(authClient);
				sync.setClickable(false);

			}
		});

	}

	protected void onResume() {
		super.onResume();

		// called only first time when allowing the application
		//to use the email address
		if (flag == 1){
			new ClientAuthentication(this.getApplicationContext(), nosql)
					.execute(account);
		}

	}

	/**
	 * Method for displaying all the notes in the database
	 * 
	 * @throws ParseException
	 */
	private void displayAllNotes() throws ParseException {
		ContentResolver provider = getContentResolver();

		String[] projection = new String[] { Notes._ID, Notes.TITLE, Notes.NOTE,
				Notes.CREATED_DATE};
		Uri queryUri = Notes.CONTENT_URI;
		/* Create a query */
		Cursor mCur = provider.query(queryUri, projection, null, null, null);

		/* Use the Cursor to move through the objects */
		if (mCur.moveToFirst()) {
			Notes currentNote = new Notes();

			do {
				currentNote = getCurrentNote(mCur);

				/* Display the notes found in the database */
				Toast.makeText(
						CurrentTasksActivity.this,
						currentNote.getTitle() + " " + currentNote.getNote()
								+ " " + currentNote.getCreatedDate(),
						Toast.LENGTH_SHORT).show();



			} while (mCur.moveToNext());
		}

		mCur.close();
	}

	/**
	 * Method used to initialize a new Note object with the current Strings from
	 * the database
	 * 
	 * @param mCur
	 *            The cursor used to move through the query results
	 * @return The Note object newly initialized
	 * @throws ParseException
	 */
	private Notes getCurrentNote(Cursor mCur) throws ParseException {
		Notes note = new Notes();

		note.setId(mCur.getString(mCur.getColumnIndex(Notes._ID)));
		note.setTitle(mCur.getString(mCur.getColumnIndex(Notes.TITLE)));
		note.setNote(mCur.getString(mCur.getColumnIndex(Notes.NOTE)));

		Long date_str = mCur.getLong(mCur.getColumnIndex(Notes.CREATED_DATE));

//		DateFormat formatter;
//		Date date;
//		formatter = new SimpleDateFormat("dd-MMM-yyyy");
//		date = (Date) formatter.parse(date_str);

		note.setCreatedDate(date_str);

		return note;
	}

	public class ClientAuthentication extends
			AsyncTask<Account, Void, DefaultHttpClient> {

		private DefaultHttpClient http_client = new DefaultHttpClient();
		/* The Context of the application */
		private Context mainActivity;
		/* The ServerDatabase object */
		private SyncServerDatabase nosql;

		public ClientAuthentication(Context context, SyncServerDatabase nosql) {

			this.mainActivity = context;
			this.nosql = nosql;
		}

		@Override
		protected DefaultHttpClient doInBackground(Account... params) {

			AccountManager accountManager = AccountManager.get(mainActivity);
			Account account = params[0];

			accountManager.getAuthToken(account, "ah", false,
					new GetAuthTokenCallback(), null);

			return http_client;
		}

		private class GetAuthTokenCallback implements
				AccountManagerCallback<Bundle> {

			public void run(AccountManagerFuture<Bundle> result) {
				Bundle bundle;
				try {
					bundle = result.getResult();
					Intent intent = (Intent) bundle
							.get(AccountManager.KEY_INTENT);

					if (intent != null) {
						// User input required
						mainActivity.startActivity(intent);
						//set flag for onResume method(the authentication should
						//be called againg)
						flag = 1;
					} else {

						String auth_token = bundle
								.getString(AccountManager.KEY_AUTHTOKEN);

						// Don't follow redirects
						http_client.getParams().setBooleanParameter(
								ClientPNames.HANDLE_REDIRECTS, false);

						HttpGet http_get = new HttpGet(
								"http://3dforandroid.appspot.com/_ah"
										+ "/login?continue=http://localhost/&auth="
										+ auth_token);

						HttpResponse response = http_client.execute(http_get);

						if (response.getStatusLine().getStatusCode() != 302) {
							// Response should be a redirect
							return;
						}

						for (Cookie cookie : http_client.getCookieStore()
								.getCookies()) {
							if (cookie.getName().equals("ACSID")) {
								authClient = http_client;
								new ReadNote(mainActivity, nosql, list)
										.execute(http_client);
							}
						}

					}
				} catch (OperationCanceledException e) {
					e.printStackTrace();
				} catch (AuthenticatorException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					http_client.getParams().setBooleanParameter(
							ClientPNames.HANDLE_REDIRECTS, true);
				}

				return;
			}
		};

	}

}